package cn.com.wxd.service.address;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.com.wxd.common.CharUtil;
import cn.com.wxd.common.JsonUtil;
import cn.com.wxd.common.net.HttpClientUtil;
import cn.com.wxd.service.cache.RedisUtil;

/**
 * Title:从新浪API获取到的用户地址（根据IP）
 * Description:从远程获取用户地址
 * <p>
 * Company: Amumu
 * Copyright: Copyright (c) 2015
 * All right reserved.
 * Created time: 2016-1-22 上午11:14:32
 *
 * @author WangXuDong
 * @version 1.0
 */
public class AddressService {
    private static final Logger log = LoggerFactory.getLogger(AddressService.class);

    private static final String ACCESSADDRESSCACHE = "accessAddressCache";
    private static final String path = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=";

    /**
     * 根据IP获取地址
     *
     * @param request reqeust
     * @param encoding
     *
     * @return
     *
     * @throws Exception
     */
    public AddressBean getAddress(HttpServletRequest request, String encoding) throws Exception {
        String ip = request.getRemoteAddr();
        getRemortIP(request);
        if (ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1") || ip.contains("localhost")) {
            return null;
        }

        //先尝试从缓存中中获取这个人的地址信息
        AddressBean addressBean = (AddressBean) RedisUtil.getObject(ACCESSADDRESSCACHE + ip);
        if (addressBean != null) {
            return addressBean;
        }

        String returnStr = getRs(path, ip);

        JSONObject json;
        AddressBean ab = null;
        if (returnStr != null) {

            json = JsonUtil.jsonToJsonObject(returnStr);

            if (1 == json.getInteger("ret")) {
                ab = new AddressBean();
                ab.setCountry(revert(json.getString("country")));//国家
                ab.setArea(revert(json.getString("district")));//地区
                ab.setProvince(revert(json.getString("province")));//省份
                ab.setCity(revert(json.getString("city")));//市区
                ab.setCounty(revert(json.getString("district")));//县
                ab.setIsp(revert(json.getString("isp")));//ISP公司

                //将当前用户的IP对应的地址信息存入缓存中
                RedisUtil.setObject(ACCESSADDRESSCACHE + ip, ab, 43200); //保存12小时
            }
        }
        return ab;

    }

    /**
     * 从url获取结果
     *
     * @param path
     * @param ip
     *
     * @return
     */
    private String getRs(String path, String ip) {
        return HttpClientUtil.doGet(path + ip);
    }

    /**
     * 字符转码
     *
     * @param str theString
     *
     * @return
     */
    private static String revert(String str) {
        str = (str == null ? "" : str);
        if (str.indexOf("\\u") == -1)//如果不是unicode码则原样返回
        {
            return str;
        }

        StringBuffer sb = new StringBuffer(1000);

        for (int i = 0; i < str.length() - 6; ) {
            String strTemp = str.substring(i, i + 6);
            String value = strTemp.substring(2);
            int c = 0;
            for (int j = 0; j < value.length(); j++) {
                char tempChar = value.charAt(j);
                int t = 0;
                switch (tempChar) {
                    case 'a':
                        t = 10;
                        break;
                    case 'b':
                        t = 11;
                        break;
                    case 'c':
                        t = 12;
                        break;
                    case 'd':
                        t = 13;
                        break;
                    case 'e':
                        t = 14;
                        break;
                    case 'f':
                        t = 15;
                        break;
                    default:
                        t = tempChar - 48;
                        break;
                }

                c += t * ((int) Math.pow(16, (value.length() - j - 1)));
            }
            sb.append((char) c);
            i = i + 6;
        }
        return sb.toString();
    }

    /**
     * 获取客户端IP
     *
     * @param request request
     *
     * @return IP
     */
    private String getRemortIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (!CharUtil.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (!CharUtil.isEmpty(ip) && !"unknown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }
}
